package com.cci.kangdao.aop;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.cci.kangdao.dto.BaseResponse;
import com.cci.kangdao.utilTool.ParameterTool;
import com.cci.kangdao.utilTool.RequestContextHolder;

/**
 * @author William Du
 * @date 2020/4/27
 */
@Component
@Aspect
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestBodyIntercept {

	private static final Logger logger = Logger.getLogger(RequestBodyIntercept.class);

	/**
	 * 拦截postJson相关请求
	 * 
	 * @param proceedingJoinPoint
	 * @return
	 */
	@Around("(execution(* com.cci.kangdao.fieldService.controller.CCGSyncController.*(..)) "
			+ "|| execution(* com.cci.kangdao.fieldService.controller.FieldServiceController.*(..)) "
			+ "|| execution(* com.cci.kangdao.escalation.controller.EscalationController.*(..)) ) "
			+ "&& @within(org.springframework.stereotype.Controller)")
	public Object around(ProceedingJoinPoint proceedingJoinPoint) {
		try {
			String requestString = ParameterTool.getRequestString(RequestContextHolder.getRequest());
			if (StringUtils.isNotEmpty(requestString)) {
				// 将请求信息字符串放入ThreadLocal
				RequestBodyThreadLocal.set(requestString);
			} else {
				// 请求json为空，尝试打印GET请求参数
				ParameterTool.getParameterRequest(RequestContextHolder.getRequest(), true);
			}
			Object object = proceedingJoinPoint.proceed();
			if (object != null && object instanceof BaseResponse) {
				logger.info("响应参数：" + JSON.toJSONString(object));
			}
			return object;
		} catch (Throwable throwable) {
			logger.error(throwable.getMessage(), throwable);
			ParameterTool.writeErrorResponse(RequestContextHolder.getResponse());
		} finally {
			// 清除ThreadLocal值，防止异常线程调用
			RequestBodyThreadLocal.clear();
		}
		return null;
	}

}
